﻿using Saber.Infrastructure;
using Saber.Infrastructure.Storage;
using Saber.Plugin.NtfsSearch.QueryEngine;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Controls;


namespace Saber.Plugin.NtfsSearch
{



    public class Main : IPlugin, ISettingProvider, ISavable, IContextMenu
    {


        private readonly SettingsViewModel viewModel;

        private Loading loading;


        private Settings _settings;
        private readonly PluginJsonStorage<Settings> _settingsStorage;

        private static PluginInitContext context { get; set; }

        private static PluginMetadata metadata;


        private Result[] commands;


        static Main()
        {

            metadata = new PluginMetadata();
            metadata.ID = "d555604215a311eb8a28ec388f76f890";
            metadata.Name = "NTFS检索";
            metadata.Description = "通过USN检索NTFS";
            metadata.ActionKeyword = "*";
            metadata.IcoPath = "Images\\find.png";
        }

        public Main()
        {
            commands = Commands();

            _settingsStorage = new PluginJsonStorage<Settings>();
            _settings = _settingsStorage.Load();

            viewModel = new SettingsViewModel();
        }

        public List<Result> Query(Query query)
        {

            var results = new List<Result>();


            var command = commands.AsParallel().Select(c =>
            {
                var titleScore = StringMatcher.Score(c.Title, query.Search);
                var subTitleScore = StringMatcher.Score(c.SubTitle, query.Search);
                var score = Math.Max(titleScore, subTitleScore);
                if (score > 0)
                {
                    c.Score = score;
                    return c;
                }
                return null;
            }).Where(r => r != null);
            results.AddRange(command);

            if (!loading.IsLoading && loading.Files != null)
            {

                var results1 = loading.Files.AsParallel().Select(p => p.Result(query.Search, context.API)).Where(r => r != null);
                results.AddRange(results1);
                results1 = null;
            }

            return results;
        }

        public List<Result> LoadContextMenus(Result selectedResult)
        {
            var entry = selectedResult.ContextData as FileAndDirectoryEntry;
            if (entry != null)
            {
                var contextMenus = new List<Result>
            {
                new Result
                {
                    Title = "以管理员身份运行",
                    Action = _ =>
                    {
                        var info = new ProcessStartInfo
                        {
                            FileName = entry.FullFileName,
                            WorkingDirectory = entry.Path,
                            Verb = "runas"
                        };
                        var hide = Main.StartProcess(info);
                        return hide;
                    },
                    IcoPath = "Images/cmd.png"
                },
                new Result
                {
                    Title = "打开所属文件夹",
                    Action = _ =>
                    {
                        var hide = Main.StartProcess(new ProcessStartInfo(entry.Path));
                        return hide;
                    },
                    IcoPath = "Images/folder.png"
                }
            };
                return contextMenus;
            }
            else
            {
                return new List<Result>();
            }
        }



        public void Init(PluginInitContext _context)
        {
            context = _context;


            loading = new Loading(_settings);

            viewModel.Loading = loading;
            loading.context = context;
            loading.Load();

        }


        public PluginMetadata Metadata()
        {
            return metadata;
        }

        public Control CreateSettingPanel()
        {
            NtfsSearchSettings set = new NtfsSearchSettings(context, _settings, viewModel, loading);

            return set;
        }

        public void Save()
        {
            _settingsStorage.Save();
        }


        private Result[] Commands()
        {
            return new[]
            {
                new Result
                {
                    Title = "Reload",
                    SubTitle = "重新加载",
                    IcoPath = "Images\\find.png",
                    Action = c =>
                    {
                        loading.Load();
                        return true;
                    }
                }
            };
            
        }


        public static bool StartProcess(ProcessStartInfo info)
        {
            bool hide;
            try
            {
                Process.Start(info);
                hide = true;
            }
            catch (Exception)
            {
                var name = "Plugin: NtfsSearch";
                var message = $"Can't start: {info.FileName}";
                context.API.ShowMsg(name, message, string.Empty);
                hide = false;
            }
            return hide;
        }
    }
}
